package com.huishu.tcm.task;

import com.huishu.tcm.vo.VerificationCodeVo;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

@EnableScheduling
@Component
public class VerificationCodeService {

    // 全局验证码列表
    public static List<VerificationCodeVo> verificationCodeVoList = new ArrayList<>();

    // 添加验证码
    public static synchronized void addVerificationCode(VerificationCodeVo v){
        verificationCodeVoList.add(v);
    }

    // 删除验证码
    public static synchronized void removeVerificationCode(String telNum){
        for(int i = verificationCodeVoList.size() - 1; i >=0; i--){
            VerificationCodeVo v = verificationCodeVoList.get(i);
            if(v.getTelNum().equals(telNum)){
                verificationCodeVoList.remove(i);
            }
        }
    }

    //  每分钟清除过期的验证码
    @Scheduled(cron = "0 0/1 * * * ?")
    public void clearExpiredVerificationCode(){
        for(int i = verificationCodeVoList.size() - 1; i >=0; i--){
            Date now = new Date();
            VerificationCodeVo v = verificationCodeVoList.get(i);
            if(now.after(v.getExpirationDate())){
                removeVerificationCode(v.getTelNum());
            }
        }
    }


}
